var express = require('express');
var app = express();
var websocket = require("./websocket-example");
var net = require("net");

var remotePort = 5834;
var remoteHost = "127.0.0.1";

websocket.listen(8080, "0.0.0.0", function(websocket) {
    // set up backend TCP connection
    var tcpsocket = new net.Socket();
    tcpsocket.connect(remotePort, remoteHost);

    // TCP handler functions
    tcpsocket.on("connect", function() {
      console.log("TCP connection open");
      var httpget = "GET " + websocket.uri + "&protocol=tcp";
      tcpsocket.write(httpget);
    });
    tcpsocket.on("data", function(data) {
      websocket.send(data);
    });
    tcpsocket.on("error", function() {
      console.log("TCP connection error", arguments);
    });

    // WebSocket handler functions
    websocket.on("data", function(opcode, data) {
       console.log('DATA ' + ":" + data);
        tcpsocket.write(data);
    });
    websocket.on("close", function(code, reason) {
        console.log("WebSocket closed")
        // close backend connection
        tcpsocket.end();
    });

    console.log("WebSocket connection open");
});

app.use(express.static('html'));
var server = app.listen(10080, function () {
    var port = server.address().port;
    console.log('listening at port:%s', port);
});